<script setup lang="ts">
import {ref, watch} from "vue";
import TaskInput from "@/components/TaskInput.vue";
// 响应式对象
//定义一个接口
interface ITASKItem{
  id:number;
  text:string;
  isDone:boolean;
  isEdit:boolean;
}
let todoText = ref('');

let taskList = ref<ITASKItem[]>([]);//指明数组的范型

taskList.value = JSON.parse(
    window.localStorage.getItem('taskList')??"[]"//如果？？左边是空，就用右边的值替换
);// 反串行化

// 这是一个侦听器。当 taskList 发生变化时，使用 onSave
watch(taskList,onSave,{deep:true});

function  onAddTask(taskText:string){
  taskList.value.push(
      {
        id:taskList.value.length+1,
        text:taskText,
        isDone:false,
        isEdit:false
      }
  )
  todoText.value='';


}

function onSave(){
                  window.localStorage.setItem('taskList',JSON.stringify(taskList.value));
//   key-value（串行化，把内存中的复杂对象转化成字符串）
}
let itemText = ref();

function onEdit(item:ITASKItem){
  item.isEdit=true;
  itemText.value=item.text;
}

function onEditOk(item:ITASKItem){
  item.isEdit=false;
  item.text=itemText.value;
}

function onDelete(item:ITASKItem){
  taskList.value = taskList.value.filter(it=>it!==item);
}

</script>

<template>
  <div class="container">
    <h1>ToDo List</h1>

    <TaskInput @addTask="onAddTask"></TaskInput>

    <div class="task-list">
      <div  v-for="item of taskList" class="task-item">
        <template v-if="!item.isEdit">
          <el-checkbox v-model="item.isDone" size="large">{{item.text}}</el-checkbox>
          <div>
            <el-button type="primary" @click="onEdit(item)">修改</el-button>
            <el-button type="danger" @click="onDelete(item)">删除</el-button>
          </div>
        </template>

        <template v-else>
          <el-checkbox v-model="item.isDone" size="large">
            <el-input v-model="itemText"></el-input>
            <el-button @click="onEditOk(item)">确定</el-button>
            <el-button @click="item.isEdit=false">取消</el-button>
          </el-checkbox>
        </template>
      </div>
    </div>
  </div>

</template>

<style scoped>
.container{
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 80%;
  margin: 0 auto;
  background-color: #f3f3f3;
}

h1{
  text-align: center;
  margin-top: 20px;
}


.task-list{
  padding:0 2em;
}
.task-item{
  display:flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
}
</style>
